package com.whq.thrift.api.web.base.serviceconf.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.whq.common.StringUtil;
import com.whq.thrift.api.common.constants.CommonConfigConstants;
import com.whq.thrift.api.common.constants.CommonErrorCodeConstants;
import com.whq.thrift.api.web.base.serviceconf.db.ModuleInfo;
import com.whq.thrift.api.web.base.serviceconf.db.ModuleInstance;
import com.whq.thrift.api.web.base.serviceconf.db.UrlMappingInfo;
import com.whq.thrift.api.web.base.serviceconf.service.ModuleInfoService;
import com.whq.thrift.api.web.base.serviceconf.service.ModuleInstanceService;
import com.whq.thrift.api.web.base.serviceconf.service.UrlMappingInfoService;

/**
 * @author whq-mac
 *
 */

@Controller
@Scope("prototype")
public class IndexController {
	private static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class);
	
	@Autowired
	private ModuleInfoService moduleInfoService;

	@Autowired
	private ModuleInstanceService moduleInstanceService;

	@Autowired
	private UrlMappingInfoService urlMappingInfoService;
	
	@RequestMapping(value="getServiceInstance")
	@ResponseBody
	public Map<String, Object> getServiceInstance(Model model,
			@RequestParam(value = "moduleIds", required = false) String moduleIds, 
	        HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>(0);
		modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_CODE, 	CommonErrorCodeConstants.ERR_CODE_SUCCESS);
		modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_MESSAGE, CommonErrorCodeConstants.MAP_ERR_CODE_MSG.get(CommonErrorCodeConstants.ERR_CODE_SUCCESS));
		
		if (StringUtil.isBlank(moduleIds)) {
			modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_CODE, 	CommonErrorCodeConstants.ERR_CODE_LACK_PARAM);
			modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_MESSAGE, "缺少参数：moduleIds");
			return modelMap;
		}
		
		List<ResponseModuleInfo> moduleList = new ArrayList<ResponseModuleInfo>(0);
		
		String[] moduleids = moduleIds.split(",");
		for (String moduleId : moduleids) {
			if (StringUtil.isNotBlank(moduleId)) {
				ModuleInfo info = null; 
				try {
					info = moduleInfoService.findRecordById(moduleId);
				} catch (Exception e) {
					LOGGER.error("moduleInfoService.findRecordById exception: ", e);
					
					modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_CODE, 	CommonErrorCodeConstants.ERR_CODE_CALL_SERVICE_METHOD_ERROR);
					modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_MESSAGE, "call spring service: moduleInfoService.findRecordById error");
					return modelMap;
				}
				if ( (info != null) && (info.getModuleStatus() == 1) ) {
					ResponseModuleInfo oneModuleInfo = new ResponseModuleInfo();
					oneModuleInfo.setModuleId(moduleId);
					
					List<ModuleInstance> instancelist = null;
					try {
						instancelist = moduleInstanceService.getRecordsByStatus(moduleId, 1);
					} catch (Exception e) {
						LOGGER.error("moduleInstanceService.getRecordsByStatus exception: ", e);
						modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_CODE, 	CommonErrorCodeConstants.ERR_CODE_CALL_SERVICE_METHOD_ERROR);
						modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_MESSAGE, "call spring service: moduleInstanceService.getRecordsByStatus error");
						return modelMap;
					}
					List<IpPortInfo> instanceList = new ArrayList<IpPortInfo>(0);
					if (instancelist != null && instancelist.size() > 0){
						for (ModuleInstance instance:instancelist) {
							if (instance == null) {
								continue;
							}
							
							IpPortInfo instancdMask = new IpPortInfo();
							instancdMask.setIp(instance.getIp());
							instancdMask.setPort(instance.getPort());
							instanceList.add(instancdMask);
						}
					} 
					oneModuleInfo.setInstanceList(instanceList);
					
					moduleList.add(oneModuleInfo);
				} 
			}
		}
		
		modelMap.put(CommonConfigConstants.API_RESPONSE_DATA, 	moduleList);
		return modelMap;
	}
	
	@RequestMapping(value="getGatewayInstances")
	@ResponseBody
	public Map<String, Object> getGatewayInstances(Model model,
	        HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>(0);
		modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_CODE, 	CommonErrorCodeConstants.ERR_CODE_SUCCESS);
		modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_MESSAGE, CommonErrorCodeConstants.MAP_ERR_CODE_MSG.get(CommonErrorCodeConstants.ERR_CODE_SUCCESS));
		
		List<ModuleInfo> moduleinfoList;
		try {
			moduleinfoList = moduleInfoService.findIsGateWayRecords(1, 1);
			LOGGER.debug("moduleinfoList.size:" + moduleinfoList.size());
		} catch (Exception e) {
			LOGGER.error("moduleInfoService.findIsGateWayRecords exception: ", e);
			modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_CODE, 	CommonErrorCodeConstants.ERR_CODE_CALL_SERVICE_METHOD_ERROR);
			modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_MESSAGE, "call spring service: moduleInfoService.findIsGateWayRecords error");
			return modelMap;
		}
		
		List<ResponseModuleInfo> moduleList = new ArrayList<ResponseModuleInfo>(0);
		
		for (ModuleInfo info : moduleinfoList) {
			if (info != null) {
				String moduleId = info.getModuleId();
				
				ResponseModuleInfo oneModuleInfo = new ResponseModuleInfo();
				oneModuleInfo.setModuleId(moduleId);
				
				List<ModuleInstance> instancelist = null;
				try {
					instancelist = moduleInstanceService.getRecordsByStatus(moduleId, 1);
				} catch (Exception e) {
					LOGGER.error("moduleInstanceService.getRecordsByStatus exception: ", e);
					modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_CODE, 	CommonErrorCodeConstants.ERR_CODE_CALL_SERVICE_METHOD_ERROR);
					modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_MESSAGE, "call spring service: moduleInstanceService.getRecordsByStatus error");
					return modelMap;
				}
				List<IpPortInfo> instanceList = new ArrayList<IpPortInfo>(0);
				if (instancelist != null && instancelist.size() > 0){
					for (ModuleInstance instance:instancelist) {
						if (instance == null) {
							continue;
						}
						
						IpPortInfo instancdMask = new IpPortInfo();
						instancdMask.setIp(instance.getIp());
						instancdMask.setPort(instance.getPort());
						instanceList.add(instancdMask);
					}
				} 
				oneModuleInfo.setInstanceList(instanceList);
				
				moduleList.add(oneModuleInfo);
			} 
		}
		
		modelMap.put(CommonConfigConstants.API_RESPONSE_DATA, 	moduleList);
		return modelMap;
	}
	
	@RequestMapping(value="getUrlMappings")
	@ResponseBody
	public Map<String, Object> getUrlMappings(Model model,
	        HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>(0);
		modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_CODE, 	CommonErrorCodeConstants.ERR_CODE_SUCCESS);
		modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_MESSAGE, CommonErrorCodeConstants.MAP_ERR_CODE_MSG.get(CommonErrorCodeConstants.ERR_CODE_SUCCESS));
		
		List<UrlMappingInfo> list;
		try {
			list = urlMappingInfoService.findAllUrlMappingInfo();
		} catch (Exception e) {
			LOGGER.error("urlMappingInfoService.findAllUrlMappingInfo exception: ", e);
			modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_CODE, 	CommonErrorCodeConstants.ERR_CODE_CALL_SERVICE_METHOD_ERROR);
			modelMap.put(CommonConfigConstants.API_RESPONSE_RETURN_MESSAGE, "call spring service: findAllUrlMappingInfo.findUrlMappingInfo error");
			return modelMap;
		}
		
		List<ResponseUrlMappingInfoMask> responseList = new ArrayList<ResponseUrlMappingInfoMask>(0);
		
		if (list != null) {
			for (UrlMappingInfo info: list) {
				if (info == null) {
					continue;
				}
				ResponseUrlMappingInfoMask infomask = new ResponseUrlMappingInfoMask();
				infomask.setUrl(info.getUrl());
				infomask.setMapParamMethod(info.getMapParamMethod());
				responseList.add(infomask);
			}
		}
		
		modelMap.put(CommonConfigConstants.API_RESPONSE_DATA, 	responseList);
		return modelMap;
	}
}

